<template>
  <div class="min-h-[700px]">
    <splitpane :splitSet="settingLR">
      <template v-slot:paneL>
        <div class="h-full min-h-[700px]">
          <treeList :key="keayvalue" ref="treeListRef" :treeProops="treeProops" :treeEvents="treeEvents"
            :pageShow="false" :inputShow="false" />
        </div>
      </template>
      <template #paneR>
        <div class="pl-[16px] pr-[5px]">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="changes($event)">
            <el-tab-pane label="已添加" name="1"> </el-tab-pane>
            <el-tab-pane label="未添加" name="2"> </el-tab-pane>
          </el-tabs>
          <div class="flex justify-between">
            <div v-if="activeName == '1'">
              <div v-auth="'business.alarm.strategy.deviceDel'">
                <el-button type="primary" :disabled="selectionData.length < 1" plain @click="cancelall(1)">取消</el-button>
                <el-button type="primary" plain @click="cancelall(2)">全部取消</el-button>
              </div>
            </div>
            <div v-if="activeName == '2'">
              <div v-auth="'business.alarm.strategy.deviceAdd'">
                <el-button type="primary" :disabled="selectionData.length < 1" plain @click="adddevice(1)">添加</el-button>
                <el-button type="primary" plain @click="adddevice(2)">全部添加</el-button>
              </div>
            </div>
            <div class="felx">
              <el-form label-width="auto" inline>
                <el-form-item label="产品类型" prop="productId" style="width: 220px;">
                  <opateproductSelect style="width: 100%" v-model="listParams.productId" />
                </el-form-item>
                <el-form-item label="设备序列号" prop="" style="width: 370px;">
                  <div class="flex">
                    <el-input placeholder="请输入设备序列号" v-model="listParams.deviceSN"></el-input>
                    <el-button type="primary" class="ml-[16px]" @click="getList">搜索</el-button>
                    <sj-button custom-type="sinfo" @click="resetting">重置</sj-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <pure-table :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
            @selection-change="selectionChange" :isShowPag="false" :key="key">
          </pure-table>
          <div class="mt-5">
            <el-pagination v-model:current-page="listParams.page" v-model:page-size="listParams.limit" background
              :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getList" @current-change="getList" />
          </div>
        </div>
      </template>
    </splitpane>
  </div>
</template>
<script setup lang="ts">
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import opateproductSelect from "@/components/select/opateproductSelect/opateproductSelect.vue";
import { ref, onMounted, reactive } from "vue";
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import { ElMessage, ElMessageBox } from "element-plus";
import treeList from "@/components/treeList/treeList.vue";
const selectionData = ref([]);
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
const operate = usePageVariablesStoreHook().getOperate();
import { facilitbuildings } from "@/api/operate/timed-tasks/index";
import { formValidateField } from '@/utils/functions'
import {
  strategylist,
  addstrategy,
  delstrategy
} from "@/api/operate/alarm-management/alarm-strategy";
const tableData = reactive({
  data: [],
  total: 0
});
import { PAGE_LAYOUT } from "@/constant";
const treeData = ref({
  data: []
});
const settingLR: ContextProps = reactive({
  minPercent: 10,
  maxPercent: 10,
  defaultPercent: 20,
  split: "vertical"
});
const activeName = ref("1");
const roleTableConfig = [
  { type: "selection", align: "left" },
  { prop: "id", label: "编号", width: 100 },
  { prop: "productName", label: "产品类型" },
  { prop: "deviceName", label: "设备别名" },
  { prop: "productName", label: "设备信息" },
  { prop: "deviceSN", label: "设备序列号" }
];
const treeRef = ref(null);
//列表参数
const listParams = ref({
  isAdd: activeName.value == "1" ? true : false,
  page: 1,
  limit: 10,
  drawingId: "", //所属楼层
  buildingId: "", //所属建筑
  deviceId: "", //设备序列号
  productId: "", //产品ID
  deviceSN: "" //设备序列号
});
const defaultSearchForm = () => {
  return {
    isAdd: listParams.value.isAdd,
    page: 1,
    limit: 10,
    drawingId: "", //所属楼层
    deviceId: "", //所属建筑
    deviceSN: "", //设备序列号
    productId: "" //产品ID
  };
};
const key = ref(0);
//获取列表
const getList = () => {
  strategylist({ ...listParams.value, strategyId: props.id }).then(res => {
    if (res.code == 200) {
      const rest: any = res;
      tableData.data = rest.result.data;
      tableData.total = rest.result.total;
    }
  });
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(listParams.value, defaultSearchForm());
  key.value++;
  getList();
};
const projectList = ref([]);
const props = defineProps({
  id: {
    type: Number,
    default: 0
  }
});
const propsa = {
  label: "buildingName",
  value: "buildingId",
  children: "children"
};
const filterMethod = (query, node) => {
  return node.buildingName.includes(query);
};
const treeProops = ref({
  props: propsa,
  data: projectList,
  "item-size": 46,
  "filter-method": filterMethod,
  nodeKey: "buildingId",
  "highlight-current": true
});
//数形事件
const isLoading = ref(true);
const treeListRef = ref();
const checkedUnitId = ref(null);
const handleNodeClick = data => {
  listParams.value.drawingId = "";
  listParams.value.buildingId = "";
  if (data.drawingName) {
    listParams.value.drawingId = data.drawingId;
    getList();
  } else {
    listParams.value.buildingId = data.buildingId;
    getList();
  }
  //   loadProjectList();
};
const changes = e => {
  if (e.props.name === "1") {
    listParams.value.isAdd = true;
  } else {
    listParams.value.isAdd = false;
  }
  getList();
};
//取消和全部取消
const cancelall = type => {
  if (type == 1) {
    delstrategy({
      id: props.id,
      deviceIds: selectionData.value.map(item => item.id),
      projectId: operate.checkedProject,
      isAll: false
    }).then(res => {
      if (res.code == 200) {
        getList();
        selectionData.value = [];
        ElMessage.success(res.msg);
      } else {
        ElMessage({
          type: "error",
          message: res.msg
        });
      }
    });
  } else {
    delstrategy({
      id: props.id,
      deviceIds: selectionData.value.map(item => item.id),
      isAll: true,
      projectId: operate.checkedProject
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: res.msg
        });
        getList();
        selectionData.value = [];
      } else {
        ElMessage({
          type: "error",
          message: res.msg
        });
      }
    });
  }
};
//添加和全部添加
const adddevice = type => {
  if (type == 1) {
    addstrategy({
      id: props.id,
      deviceIds: selectionData.value.map(item => item.id),
      isAll: false,
      projectId: operate.checkedProject
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: res.msg
        });
        getList();
        selectionData.value = [];
      } else {
        ElMessage({
          type: "error",
          message: res.msg
        });
      }
    });
  } else {
    addstrategy({
      id: props.id,
      deviceIds: selectionData.value.map(item => item.id),
      projectId: operate.checkedProject,
      isAll: true
    }).then(res => {
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getList();
        selectionData.value = [];
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};
const selectionChange = data => {
  selectionData.value = data;
};
const defultProjectList = () => [];
const treeEvents = {
  nodeClick: handleNodeClick
};
const keayvalue = ref(0);
const checkedProject = ref(0);
//获取数据
const loadProjectList = () => {
  return new Promise((resolve, reject) => {
    isLoading.value = true;
    facilitbuildings()
      .then(res => {
        if (res.result.buildingInfo.length > 0) {
          res.result.buildingInfo.forEach(item => {
            if (item.children.length > 0) {
              item.children.forEach(item1 => {
                item1.buildingId = item1.drawingId + "-1" + item.buildingId;
                item1.buildingName = item1.drawingName;
              });
            }
          });

          res.result.buildingInfo.unshift({
            buildingId: "0",
            buildingName: "全部",
            children: []
          });
          projectList.value = res.result.buildingInfo;
        }
      })
      .finally(() => {
        isLoading.value = false;
        resolve("");
      });
    checkedProject.value = 0;
  }
  )
};
const open = () => {
  loadProjectList().then(() => {
    treeListRef.value
      .getTreeRef()
      .setCurrentKey(projectList.value[0].buildingId);
    listParams.value.buildingId = projectList.value[0].buildingId;
    resetting();
  });
};
onMounted(() => {
  open();
});
</script>
